<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="主体" prop="orgguid">
        <el-select v-model="queryParams.orgguid" placeholder="请选择主体" clearable size="small">
          <el-option
            v-for="dict in orgs"
            :key="dict.guid"
            :label="dict.name"
            :value="dict.guid"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="物流公司" prop="supplierId">
        <el-select v-model="queryParams.supplierId" placeholder="请选择物流公司" clearable size="small">
          <el-option
            v-for="dict in suppliers"
            :key="dict.id"
            :label="dict.name"
            :value="dict.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="起止日期">
        <el-date-picker clearable size="small" style="width: 200px" v-model="queryParams.beginTime" type="date" value-format="yyyy-MM-dd" placeholder="选择开始日期">
        </el-date-picker>
        <el-date-picker clearable size="small" style="width: 200px" v-model="queryParams.endTime" type="date" value-format="yyyy-MM-dd" placeholder="选择结束日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="状态" prop="stats">
        <el-select v-model="stats" placeholder="请选择状态" clearable size="small"  filterable multiple>
          <el-option
            v-for="dict in statusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="parseInt(dict.dictValue)"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-if="permission.includes(63)"
        >新增</el-button>
      </el-col>
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="success"-->
<!--          icon="el-icon-edit"-->
<!--          size="mini"-->
<!--          :disabled="single"-->
<!--          @click="handleUpdate"-->
<!--        >发起</el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="danger"-->
<!--          icon="el-icon-delete"-->
<!--          size="mini"-->
<!--          :disabled="multiple"-->
<!--          @click="handleDelete"-->
<!--          v-hasPermi="['farepay:farepay:remove']"-->
<!--        >删除</el-button>-->
<!--      </el-col>-->
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['farepay:farepay:export']"
        >导出</el-button>
      </el-col>
	  <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="farepayList" @selection-change="handleSelectionChange" :show-summary="true" sum-text="合计(所有页)" :summary-method="sumIt">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="编号" align="center" prop="code" />
      <el-table-column label="主体" align="center" prop="orgname" width="160" />
      <el-table-column label="物流公司" align="center" prop="supplierName" width="220" />
<!--      <el-table-column label="发货地址" align="center" >-->
<!--        <template slot-scope="scope">-->
<!--          <span>{{ scope.row.deliprovince + scope.row.delicity + scope.row.delidistrict + scope.row.deliaddress }}</span>-->
<!--        </template>-->
<!--      </el-table-column>-->
      <el-table-column label="金额(元)" align="center" prop="totalamount" />
      <el-table-column label="状态" align="center" prop="statusname" />
      <el-table-column label="操作人" align="center" prop="operator" />
      <el-table-column label="操作时间" align="center" prop="createtime" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-more"
            @click="viewIt(scope.row.id)"
          >详情</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-promotion"
            @click="handleStart(scope.row)"
            v-if="scope.row.status == -1"
          >发起</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-if="scope.row.status == -1"
          >修改</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" :inline="true" label-width="120px">
        <el-form-item label="主体" prop="orgguid">
          <el-select value-key="guid" v-model="currOrg" @change="(e) => {form.orgguid = currOrg.guid; form.orgname = currOrg.name;}" clearable  placeholder="请选择付款主体">
            <el-option
              v-for="dict in orgs"
              :label="dict.name"
              :value="dict"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="部门">
          <el-input v-model="departname" clearable disabled />
        </el-form-item>
        <el-form-item label="物流公司" prop="supplierId">
          <el-select value-key="id" v-model="currSupplier" @change="(e) => {form.supplierId = currSupplier.id; form.supplierName = currSupplier.name; form.bank=currSupplier.bank; form.bankCode=currSupplier.bankcode;}" clearable  placeholder="请选择物流公司">
            <el-option
              v-for="dict in suppliers"
              :label="dict.name"
              :value="dict"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="其他费用" prop="othercost">
          <el-input v-model="form.otheramount" type="number" clearable placeholder="请输入其他费用" />
        </el-form-item>
        <el-form-item label="开户行" prop="bank">
          <el-input v-model="form.bank" type="text" clearable placeholder="请输入开户行名字" />
        </el-form-item>
        <el-form-item label="银行卡号" prop="bankCode">
          <el-input v-model="form.bankCode" type="number" clearable placeholder="请输入银行卡号" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" clearable  placeholder="请输入备注" style="width: 543px" />
        </el-form-item>
        <el-form-item label="附件" >
          <el-upload
            class="upload"
            :headers="upload.headers"
            :action="upload.url"
            :disabled="upload.isUploading"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :before-remove="beforeRemove"
            :on-success="handleUpload"
            :file-list="fileList">
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" :disabled="departname == ''" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 修改运费支付对话框 -->
    <el-dialog :title="title" :visible.sync="open2" width="800px" append-to-body>
      <el-form ref="form" :model="form" :inline="true" label-width="120px">
        <el-form-item label="主体" prop="orgguid">
          <el-input v-model="form.orgname" clearable disabled />
        </el-form-item>
        <el-form-item label="部门">
          <el-input v-model="form.departname" clearable disabled />
        </el-form-item>
        <el-form-item label="物流公司" prop="supplierId">
          <el-input v-model="form.supplierName" clearable disabled />
        </el-form-item>
        <el-form-item label="其他费用" prop="othercost">
          <el-input v-model="form.otheramount" type="number" clearable placeholder="请输入其他费用" />
        </el-form-item>
        <el-form-item label="开户行" prop="bank">
          <el-input v-model="form.bank" type="text" clearable />
        </el-form-item>
        <el-form-item label="银行卡号" prop="bankCode">
          <el-input v-model="form.bankCode" type="number" clearable />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" clearable  placeholder="请输入备注" style="width: 543px" />
        </el-form-item>
        <el-form-item label="附件" >
          <el-upload
            class="upload"
            :headers="upload.headers"
            :action="upload.url"
            :disabled="upload.isUploading"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :before-remove="beforeRemove"
            :on-success="handleUpload"
            :file-list="fileList">
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel2">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listFarepay, getFarepay, delFarepay, addFarepay, updateFarepay, exportFarepay, startFarepay } from "@/api/wlinfo/farepay";
import { getWlComp } from "@/api/organization/supplier";
import { findOrganizationList, getFareDepart, getCurrPermis } from "@/api/public";
import { getToken } from "@/utils/auth";

export default {
  name: "Farepay",
  components: {
  },
  data() {
    return {
      // 导入参数
      upload: {
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/common/uploadImage", // 上传的图片服务器地址
      },
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 运费支付表格数据
      farepayList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      open2: false,
      // 状态字典
      statusOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        manager: null,
        managertel: null,
        fintel: null,
        status: null,
        stats: [],
        statusStr: '',
        beginTime: null,
        endTime: null
      },
      stats: [],
      // 表单参数
      form: {
        departname: ''
      },
      // 表单校验
      rules: {
        name: [
          { required: true, message: "客户名称不能为空", trigger: "blur" }
        ],
      },
      orgs: [],
      suppliers: [],
      currOrg: {},
      currSupplier: {},
      depart: {},
      permission: [],
      fileList: [],
      departname: '',
      sumBalance: ''
    };
  },
  created() {
    this.queryParams.beginTime = this.getMonthFirDate();
    this.getList();
    this.getPermis();
    this.findOrganizationList();
    this.getSuppliers();
    this.getDicts("farepay_apply_status").then(response => {
      this.statusOptions = response.data;
    });
  },
  watch: {
    'form.orgguid': function(val) {
      if (!val) return;
      this.getFareDepart(val);
    }
  },
  methods: {
    sumIt(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        // index 第几列从0开始
        if (index === 1) {
          sums[1] = '合计(所有页)';
          return;
        }
        if (index === 4) {
          sums[index] = this.sumBalance;
          return;
        }
        sums[index] = '-';
      });
      return sums;
    },
    //上传相关
    handlePreview(file) {
      if (file.url) {
        let url = `http://${location.host}/prod-api${file.url}`;
        location.href = url;
      }
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${ file.name }？`);
    },
    handleUpload(response, file, fileList) {
      if (response.code == 200) {
        this.fileList.push({id: response.id, name: response.originalName, url: response.url});
        console.log('this.fileList upload:', this.fileList)
      }
    },
    handleRemove(file, fileList) {
      this.fileList = this.fileList.filter(item => {
        return item.id != file.id;
      });
    },
    getPermis() {
      getCurrPermis().then(response => {
        this.permission = response.data;
        console.log('this.permission:', this.permission)
      });
    },
    viewIt(id) {
      this.$router.push({path: '/wlinfo/farepayinfo', query: {id: id}});
    },
    //查询组织
    findOrganizationList(){
      findOrganizationList().then(response => {
        this.orgs = response.data;
      });
    },
    /** 查询物流公司列表 */
    getSuppliers() {
      getWlComp().then(response => {
        this.suppliers = response.data;
      });
    },
    /** 查询运费支付列表 */
    getList() {
      this.loading = true;
      this.queryParams.statusStr = this.stats.join(',');
      listFarepay(this.queryParams).then(response => {
        this.farepayList = response.rows;
        this.total = response.total;
        this.sumBalance = response.amount;
        this.loading = false;
      });
    },
    // 状态字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 取消按钮
    cancel2() {
      this.open2 = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        orgguid: null,
        orgname: null,
        supplierId: null,
        supplierName: null,
        departid: '',
        departname: '',
        bank: null,
        bankCode: null,
        remark: null,
      };
      this.currOrg = {};
      this.currSupplier = {};
      this.departname = '';
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.stats = [];
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加运费支付";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      console.log('row:', row)
      this.reset();
      getFarepay(row.id).then(response => {
        this.form = response.data;
        this.open2 = true;
        this.title = "修改运费支付";
        //files回显
        this.fileList = this.form.files.map(item => {
          return {
            id: item.guid,
            name: item.imagename,
            url: item.url
          }
        });
      });
    },
    /** 发起按钮操作 */
    handleStart(row) {
      const guids = row.id || this.ids;
      this.$confirm('确定要执行该操作?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        return startFarepay({id: guids});
      }).then(() => {
        this.getList();
        this.msgSuccess("发起成功");
      })
    },
    /** 查询部门**/
    getFareDepart(orgid) {
      this.departname = ''
      this.form.departid = '';
      this.form.departname = '';
      getFareDepart({orgid: orgid, permission: 63}).then(response => {
        let depart = response.data[0];
        console.log('depart:', depart)
        this.form.departid = depart.guid;
        this.form.departname = depart.name;
        this.departname = depart.name;
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          console.log('this.fileList:', this.fileList)
          this.form.fileIds = this.fileList.map(item => item.id).join(',');
          if (this.form.id != null) {
            updateFarepay(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open2 = false;
              this.getList();
            });
          } else {
            addFarepay(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const guids = row.id || this.ids;
      this.$confirm('是否确认删除该数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delFarepay(guids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有运费支付数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportFarepay(queryParams);
        }).then(response => {
          this.download(response.msg);
        })
    }
  }
};
</script>
